<template>
  <div class="app-container">
    <div class="warning-management">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>考核预警管理</h2>
        <p>管理系统预警信息，及时处理重要通知</p>
      </div>

      

      <!-- 操作栏 -->
      <div class="operation-bar">
        <el-button type="success" @click="markAllAsRead" :disabled="!hasUnread">
          <i class="el-icon-check"></i>
          全部标记已读
        </el-button>
        <el-button type="warning" @click="batchMarkAsRead" :disabled="selectedWarnings.length === 0">
          <i class="el-icon-check"></i>
          批量标记已读
        </el-button>
        <el-button type="info" @click="refreshData">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="用户名">
            <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
          <el-form-item label="预警标题">
            <el-input v-model="searchForm.title" placeholder="请输入预警标题" clearable></el-input>
          </el-form-item>
          <el-form-item label="预警类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="订单预警" value="ORDER_WARNING"></el-option>
              <el-option label="考核预警" value="SCORE_WARNING"></el-option>
              <el-option label="白单预警" value="WHITE_ORDER_WARNING"></el-option>
              <el-option label="蓝单预警" value="BLUE_ORDER_WARNING"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="阅读状态">
            <el-select v-model="searchForm.isRead" placeholder="请选择状态" clearable>
              <el-option label="未读" :value="0"></el-option>
              <el-option label="已读" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchWarnings">
              <i class="el-icon-search"></i>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <i class="el-icon-refresh-left"></i>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 预警列表 -->
      <div class="warning-table">
        <el-table 
          :data="warningList" 
          v-loading="loading"
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="title" label="预警标题" min-width="180" show-overflow-tooltip></el-table-column>
          <el-table-column prop="description" label="描述" min-width="260" show-overflow-tooltip></el-table-column>
          <el-table-column prop="userName" label="用户名" min-width="120" show-overflow-tooltip></el-table-column>
          <el-table-column prop="type" label="类型" width="120">
            <template slot-scope="scope">
              <el-tag :type="getTypeTagType(scope.row.type)">
                {{ getTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isRead" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isRead === 1 ? 'success' : 'warning'">
                {{ scope.row.isRead === 1 ? '已读' : '未读' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template slot-scope="scope">
              {{ formatTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center" fixed="right">
            <template slot-scope="scope">
              <div class="action-buttons">
                <el-tooltip v-if="scope.row.isRead === 0" content="标记已读" placement="top">
                  <el-button size="mini" type="success" plain circle icon="el-icon-check" @click="markAsRead(scope.row)" />
                </el-tooltip>
                <el-tooltip content="编辑" placement="top">
                  <el-button size="mini" type="warning" plain circle icon="el-icon-edit" @click="editWarning(scope.row)" />
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button size="mini" type="danger" plain circle icon="el-icon-delete" @click="deleteWarning(scope.row)" />
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination>
        </div>
      </div>

      <!-- 创建/编辑预警对话框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="600px"
        @close="resetForm"
      >
        <el-form :model="warningForm" :rules="warningRules" ref="warningForm" label-width="100px">
          <el-form-item label="预警标题" prop="title">
            <el-input v-model="warningForm.title" placeholder="请输入预警标题"></el-input>
          </el-form-item>
          
          <el-form-item label="预警描述" prop="description">
            <el-input
              type="textarea"
              v-model="warningForm.description"
              placeholder="请输入预警描述"
              :rows="3"
            ></el-input>
          </el-form-item>

          <el-form-item label="预警类型" prop="type">
            <el-select v-model="warningForm.type" placeholder="请选择预警类型">
              <el-option label="订单预警" value="ORDER_WARNING"></el-option>
              <el-option label="考核预警" value="SCORE_WARNING"></el-option>
              <el-option label="白单预警" value="WHITE_ORDER_WARNING"></el-option>
              <el-option label="蓝单预警" value="BLUE_ORDER_WARNING"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="用户ID" prop="userId">
            <el-input-number v-model="warningForm.userId" :min="0" placeholder="0表示系统预警"></el-input-number>
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model="warningForm.remark"
              placeholder="请输入备注信息"
              :rows="2"
            ></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import { 
  getWarningList, 
  updateWarning, 
  deleteWarning, 
  markAsRead,
  batchMarkAsRead,
  markAllAsRead,
  getUnreadCount,
  getWarningStats
} from '@/api/assessAlert'

export default {
  name: 'WarningManagement',
  data() {
    return {
      loading: false,
      submitting: false,
      warningList: [],
      selectedWarnings: [],
      searchForm: {
        title: '',
        type: null,
        isRead: null
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      stats: {
        totalWarnings: 0,
        unreadWarnings: 0,
        readWarnings: 0,
        todayWarnings: 0
      },
      dialogVisible: false,
      detailDialogVisible: false,
      dialogTitle: '新建预警',
      isEdit: false,
      selectedWarning: null,
      warningForm: {
        id: null,
        title: '',
        description: '',
        type: '',
        userId: 0,
        remark: ''
      },
      warningRules: {
        title: [
          { required: true, message: '请输入预警标题', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入预警描述', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择预警类型', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    hasUnread() {
      if (!this.warningList || this.warningList.length === 0) return false
      return this.warningList.some(w => w && w.isRead === 0)
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      try {
        await Promise.all([
          this.loadWarnings(),
          this.loadStats()
        ])
      } catch (error) {
        this.$message.error('加载数据失败: ' + error.message)
      }
    },
    async loadWarnings() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await getWarningList(params)
        if (response.code === 200) {
          this.warningList = response.data.records || response.data
          this.pagination.total = response.data.total || response.data.length
        }
      } catch (error) {
        this.$message.error('加载预警列表失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    async loadStats() {
      try {
        const userId = this.$store.getters.userId || 1 // 获取当前用户ID
        const [unreadResponse, statsResponse] = await Promise.all([
          getUnreadCount(userId),
          getWarningStats(userId)
        ])
        
        if (unreadResponse.code === 200) {
          this.stats.unreadWarnings = unreadResponse.data
        }
        
        if (statsResponse.code === 200) {
          // 处理统计数据
          this.stats.totalWarnings = this.warningList.length
          this.stats.readWarnings = this.stats.totalWarnings - this.stats.unreadWarnings
          this.stats.todayWarnings = 0 // 需要根据实际数据计算
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    searchWarnings() {
      this.pagination.currentPage = 1
      this.loadWarnings()
    },
    resetSearch() {
      this.searchForm = {
          userName: '',
        title: '',
        type: null,
        isRead: null
      }
      this.pagination.currentPage = 1
      this.loadWarnings()
    },
    refreshData() {
      this.loadData()
    },
    editWarning(row) {
      this.dialogTitle = '编辑预警'
      this.isEdit = true
      this.dialogVisible = true
      this.warningForm = { ...row }
    },
    viewWarning(row) {
      this.selectedWarning = row
      this.detailDialogVisible = true
    },
    async submitForm() {
      this.$refs.warningForm.validate(async (valid) => {
        if (valid) {
          this.submitting = true
          try {
            if (!this.isEdit) {
              this.$message.error('当前不支持新建预警')
              this.submitting = false
              return
            }
            const response = await updateWarning(this.warningForm.id, this.warningForm)

            if (response.code === 200) {
              this.$message.success(this.isEdit ? '更新成功' : '创建成功')
              this.dialogVisible = false
              this.loadWarnings()
            } else {
              this.$message.error(response.msg)
            }
          } catch (error) {
            this.$message.error('操作失败: ' + error.message)
          } finally {
            this.submitting = false
          }
        }
      })
    },
    resetForm() {
      this.warningForm = {
        id: null,
        title: '',
        description: '',
        type: '',
        userId: 0,
        remark: ''
      }
      if (this.$refs.warningForm) {
        this.$refs.warningForm.resetFields()
      }
    },
    async markAsRead(row) {
      try {
        const response = await markAsRead(row.id)
        if (response.code === 200) {
          this.$message.success('标记成功')
          row.isRead = 1
          this.loadStats()
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        this.$message.error('标记失败: ' + error.message)
      }
    },
    async batchMarkAsRead() {
      if (this.selectedWarnings.length === 0) {
        this.$message.warning('请先选择要操作的预警')
        return
      }

      try {
        const ids = this.selectedWarnings.map(w => w.id)
        const response = await batchMarkAsRead(ids)
        if (response.code === 200) {
          this.$message.success('批量标记成功')
          this.loadWarnings()
          this.loadStats()
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        this.$message.error('批量标记失败: ' + error.message)
      }
    },
    async markAllAsRead() {
      try {
        // 优先对当前列表中所有未读项执行批量已读（适用于主管/admin处理下属数据）
        const unreadIds = (this.warningList || [])
          .filter(w => w && w.isRead === 0)
          .map(w => w.id)
        if (unreadIds.length > 0) {
          const resp = await batchMarkAsRead(unreadIds)
          if (resp.code === 200) {
            this.$message.success('全部标记成功')
            await this.loadWarnings()
            await this.loadStats()
            return
          } else {
            this.$message.error(resp.msg)
            return
          }
        }

        // 如果当前无数据或均为已读，则回落到按当前用户ID标记
        const userId = this.$store.getters.userId || 1
        const response = await markAllAsRead(userId)
        if (response.code === 200) {
          this.$message.success('全部标记成功')
          this.loadWarnings()
          this.loadStats()
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        this.$message.error('标记失败: ' + error.message)
      }
    },
    async deleteWarning(row) {
      try {
        await this.$confirm('确定要删除这个预警吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteWarning(row.id)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.loadWarnings()
          this.loadStats()
        } else {
          this.$message.error(response.msg)
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败: ' + error.message)
        }
      }
    },
    handleSelectionChange(selection) {
      this.selectedWarnings = selection
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadWarnings()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadWarnings()
    },
    getTypeTagType(type) {
      switch (type) {
        case 'ORDER_WARNING': return 'warning'
        case 'SCORE_WARNING': return 'danger'
        case 'WHITE_ORDER_WARNING': return 'warning'
        case 'BLUE_ORDER_WARNING': return 'danger'
        default: return 'info'
      }
    },
    getTypeText(type) {
      switch (type) {
        case 'ORDER_WARNING': return '订单预警'
        case 'SCORE_WARNING': return '考核预警'
        case 'WHITE_ORDER_WARNING': return '白单预警'
        case 'BLUE_ORDER_WARNING': return '蓝单预警'
        default: return '未知'
      }
    },
    formatTime(time) {
      if (!time) return '-'
      return new Date(time).toLocaleString()
    }
  }
}
</script>

<style scoped>
.warning-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 40px;
  margin-right: 15px;
  color: #409EFF;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.operation-bar {
  margin-bottom: 20px;
}

.search-bar {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.warning-table {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>
